import { chatConfig } from "@/config/chatConfig"
import { storeToRefs } from 'pinia'
import { clientStore, userStore, chatMapStore, userListStore, tabStore, videoStore } from '@/stores/mqttStore'
import mqtt from 'mqtt'
import { ref } from "vue";
import { showNotify } from 'vant';

const retryTimes = ref(0);
const { client } = storeToRefs(clientStore())
const { uid } = storeToRefs(userStore())
const { userList } = storeToRefs(userListStore())
const { targetChatUid } = storeToRefs(tabStore())
const { videoFlag, videoUid, videoRefuse, called, videoOffer, videoOk, videoAnswer, videoFromCandidate, videoToCandidate } = storeToRefs(videoStore())
const config = chatConfig()
const handleMsgMap = new Map()

/**
 * 连接成功处理
 */
const handleOnConnect = () => {
  console.log("connection successful");
  initSubscription()
  initHandleMsgMap()
}

const initData = () => {
  client.value = {
    connected: false,
  }

  retryTimes.value = 0
};

/**
 * 重新连接处理
 */
const handleOnReConnect = () => {
  retryTimes.value += 1;
  if (retryTimes.value > 5) {
    try {
      client.value.end();
      initData();
      console.log("connection maxReconnectTimes limit, stop retry");
    } catch (error) {
      console.log("handleOnReConnect catch error:", error);
    }
  }
}

/**
 * 连接异常处理
 */
const handleOnError = (error) => {
  console.log("connection error:", error);
}

/**
 * 收到消息处理
 */
const handleOnMessage = (topic, message) => {
  const data = JSON.parse(JSON.parse(message.toString()))
  console.log(`received message topic: ${topic} data:`, data);
  handleMsgMap.get(data.type)(topic, data)
}

/**
 * 初始化订阅主题
 */
const initSubscription = () => {
  let topicList = []
  topicList.push(uid.value)
  let allTopic = topicList.concat(config.commonTopicList)
  client.value.subscribe(allTopic, { qos: 2 }, (error, granted) => {
    if (error) {
      console.log("subscribe error:", error);
      return;
    }
    console.log("subscribe successfully:", granted);
  })
}

/**
 * 初始化连接
 */
export const conn = () => {
  if(client.value && client.value.connected){
    return
  }

  try{
    client.value = mqtt.connect(config.url, config.options);

    // https://github.com/mqttjs/MQTT.js#event-connect
    client.value.on("connect", handleOnConnect);

    // https://github.com/mqttjs/MQTT.js#event-reconnect
    client.value.on("reconnect", handleOnReConnect);

    // https://github.com/mqttjs/MQTT.js#event-error
    client.value.on("error", handleOnError);

    // https://github.com/mqttjs/MQTT.js#event-message
    client.value.on("message", handleOnMessage);

  }catch(error) {
    console.log("mqtt.connect error:", error);
  }
}

/**
 * 发布消息
 */
export const publish = (topic, msg) => {
  if(!client.value || !client.value.connected){
    conn()
  }
  client.value.publish(topic, JSON.stringify(msg), { qos: 2 }, (error) => {
    if (error) {
      console.log(`published topic:${topic} message: ${msg}`);
      return;
    }
  })
}

/**
 * 获取连接客户端
 */
export const getClient = () => {
  return client.value
}

export const addChat = (chatUid, data) => {
  chatMapStore().addChat(chatUid, data)
  addChatUser(chatUid, data)
}

export const clearChatNum = (chatUid) => {
  const chatUser = userList.value.find(i => i.uid === chatUid)
  if(chatUser){
    chatUser.num = 0
    chatUser.dot = false
  }
}

export const getChatList = (chatUid) => {
  return chatMapStore().getChatList(chatUid);
}

export const getLoginUid = () => {
  return uid.value
}

/**
 * 初始化消息处理器
 */
const initHandleMsgMap = () => {
  if(handleMsgMap.size > 0){
    return
  }
  handleMsgMap.set('chat-msg', handleChatMsg)
  handleMsgMap.set('chat-sys', handleChatSys)
  handleMsgMap.set('chat-video', handleChatVideo)
}

/**
 * 处理聊天消息
 */
const handleChatMsg = (topic, data) => {
  if(!targetChatUid.value || targetChatUid.value != data.fromUid){
    showNotify({ type: 'success', message: data.msg });
  }
  addChat(data.fromUid, data)
}

const addChatUser = (chatUid, data) => {
  const user = userList.value.find(i => i.uid === chatUid)
  if(user){
    user.data = data
    if(!targetChatUid.value || targetChatUid.value !== chatUid){
      user.num = user.num + 1
      user.dot = true
    }
    return
  }

  userList.value.push({
    avatar: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg',
    uid: chatUid,
    data: data,
    num: 1,
    dot: true
  })
}

/**
 * 处理聊天系统消息
 */
const handleChatSys = (topic, data) => {

}

/**
 * 处理视频通话消息
 */
const handleChatVideo = (topic, data) => {
  if(data.key == 'invite'){
    videoFlag.value = true
    called.value = false
    videoUid.value = data.fromUid
  }

  if(data.key == 'invite-refuse'){
    videoRefuse.value = true
  }

  if(data.key == 'invite-end'){
    videoFlag.value = false
    videoUid.value = null
    called.value = false
  }

  if(data.key == 'invite-ok'){
    videoOk.value = true
  }

  if(data.key == 'invite-offer'){
    videoOffer.value = data.data
  }

  if(data.key == 'invite-answer'){
    videoAnswer.value = data.data
  }

  if(data.key == 'invite-from-candidate'){
    videoFromCandidate.value = data.data
  }

  if(data.key == 'invite-to-candidate'){
    videoToCandidate.value = data.data
  }
}